<?php

namespace qore_base\util\collections;
use \qore\error\Exception;
use \Qore;

/**
 * @author Samuel Nogueira <samuel.nogueira.dev@gmail.com>
 */
class Configuration extends Map {

	/**
	 * Loads configuration data from a file and merges it with the existing configuration.
	 *
	 * A config file must be a PHP script returning a configuration array (like the following)
	 * <pre>
	 * return array (
	 *     'name' => 'My Application',
	 *     'defaultController' => 'index',
	 * );
	 * </pre>
	 *
	 * @param string $configFile Configuration file path (if using relative path, be aware of what is the current path)
	 * @see mergeWith
	 */
	public function loadFromFile($configFile) {
		$this->mergeWith(
			require($configFile)
		);
	}

	/** 
	 * Saves the configuration into a string.
	 * The string is a valid PHP expression representing the configuration data as an array.
	 * @return string the string representation of the configuration
	 */
	public function saveAsString() {
		return str_replace("\r", '', var_export($this->toArray(), true));
	}

	/**
	 * Applies the configuration to an object.
	 * @param object $object object to be applied with this configuration
	 * @param bool $useSetters Whether to use setters or direct association
	 */
	public function applyTo($object, $useSetters=false) {
		foreach ($this->toArray() as $key => $value) {
			if ($useSetters) {
				$setter = "set{$key}";
				$object->$setter($value);
			} else {
				$object->$key = $value;
			}
		}
	}
}
